<?php

namespace catchAdmin\propaganda\service;

use app\common\business\Answer;
use app\common\lib\ZhyxBeanstalkd;
use app\common\model\Followtask as TaskModel;
use catchAdmin\permissions\model\Users as UserModel;
use app\common\model\PatientInfo as PatientInfoModel;
use app\common\model\PropagandaEducationHistory as PEHModel;
use app\common\model\PropagandaEducation as EdModel;
use app\common\model\PropagandaEducationClass as EdClassModel;
use app\common\model\PushMessage as MessageModel;
use catcher\exceptions\FailedException;
use MongoDB\BSON\ObjectId;
use Pheanstalk\JobId;
use think\exception\FileException;
use think\facade\Log;

class EdCenterService
{
    /**
     * 发送在院宣教
     * @param array $param 参数
     * @retrun bool
     */
    public function pushData(array $param = []): bool
    {
        $allPid = [];

        if (!isset($param['is_all'])) {

            if (isset($param['pid'])) {
                if (!isset($param['pid'][0]['patientId'])) {
                    $allPid['pid'] = (new PatientInfoModel())
                        ->whereIn('id', $param['pid'])
                        ->field('id,patientId,name')
                        ->select()
                        ->each(function ($item, $key) {
                            $item['pid'] = $item['id'];
                            return $item;
                        })
                        ->toArray();
                } else {
                    $allPid['pid'] = $param['pid'];
                }
            }
            if (isset($param['all']) && !empty($param['all']) == 1) {

                $allPid['pid'] = (new PatientInfoModel())->getInEducation(2);
            }
        } else {

            $allPid['pid'] = $param['pid'];
        }

        //推送宣教参数
        $edDatas = [];

        //推送消息参数
        $messageDatas = [];

        //批次号
        $batchNo = uniqid('ed_');

        //批次名称
        $batchName = $param['batch_name'];

        foreach ($param['ed'] as $key => $val) {
            foreach ($allPid['pid'] as $k1 => $v1) {

                $history_id = new ObjectId();
                $edDatas[] = [
                    '_id' => (string)$history_id,
                    'type' => 1,//类型 1在院宣教
                    'pid' => $v1['pid'],
                    'name' => $v1['name'],
                    'patientId' => $v1['patientId'],
                    'batch_no' => $batchNo,
                    'batch_name' => $batchName,
                    'class_id' => $val['class_id'],
                    'class_name' => $val['class_name'],
                    'ed_id' => $val['ed_id'],
                    'ed_name' => $val['ed_name'],
                    'creator_id' => request()->user()->id,
                    'creator_name' => request()->user()->username,
                    'pushtime' => $param['pushtime'],
                    'pushtime_ymd' => date("Y-m-d", strtotime($param['pushtime'])),
                    'mode' => $param['mode'],
                    'isview' => 0,
                    'deleted_at' => $param['deleted_at'],
                    'sms_id' => $param['sms_id'] ?? '',
                    'sms_title' => $param['sms_title'] ?? '',
                    'status' => 0,
                    'department_id' => request()->user()->department_id ?? "",
                    'department_name' => request()->user()->userDept['department_name'] ?? "",
                    'source' => 1//来源 1 宣教计划，2 自动随访，3 异常问卷，4 其他
                ];

                $messageDatas[] = [
                    'type' => 2,//消息类型 1随访，2宣教
                    'typeName' => '宣教',
                    'mode' => $param['mode'],
                    'batch_no' => $batchNo,
                    'batch_name' => $batchName,
                    'ed_id' => $val['ed_id'],
                    'ed_name' => $val['ed_name'],
                    'class_id' => $val['class_id'],
                    'class_name' => $val['class_name'],
                    'creator_id' => $param['creator_id'],
                    'deleted_at' => $param['deleted_at'],
                    'patientId' => $v1['patientId'],
                    'pushtime' => date("Y-m-d", strtotime($param['pushtime'])),
                    'pushdatetime' => $param['pushtime'],
                    'content' => '您好' . $v1['name'] . ',为您推送' . $val['ed_name'] . '宣教内容',
                    'history_id' => (string)$history_id,
                    'isview' => 0,
                    'category' => 'Patient'
                ];
            }
        }

        //队列参数
        $pushData = [
            'batchNo' => $batchNo,
            'message' => $messageDatas,
            'tubeName' => 'SendPropagandaEducation',
        ];

        //计算延迟队列时间
        $delay = delayTime($param['pushtime']);

        $res = (new PEHModel())->saveAll($edDatas);

        if ($res) {

            Log::write("发送宣教队列参数:".json_encode($pushData, JSON_THROW_ON_ERROR), 'ed');
            ZhyxBeanstalkd::getInstance()->beansTalk->useTube("sendPropagandaEducation")->put(json_encode($pushData, JSON_THROW_ON_ERROR), 0, $delay);
        }
        return true;
    }

    /**
     * 删除宣教计划
     * @param string $batch_no 宣教批次号
     * @param string $job_id 队列id
     * @param string $pushtime 推送时间
     * @retrun bool
     */
    public function delEdhistory(string $batch_no, string $job_id, string $pushtime): bool
    {
        $diffDays = date_diff(date_create($pushtime), date_create(date("Y-m-d H:i")), false);

        if ($diffDays->invert === 1) {
            ZhyxBeanstalkd::getInstance()->beansTalk->delete(new JobId($job_id));
            $ids = (new PEHModel())->where('batch_no', $batch_no)->column('id');
            return (new PEHModel())->delData($ids);
        }
        throw new FailedException("已推送给患者，不能进行删除操作");
    }

    /**
     * 随访路径-自动推送宣教
     * @param string $patientId 患者id
     * @param string $class_id 宣教分类
     * @param string $ed_id 宣教id
     * @param string $mode 推送类型 1微信，2短信，3微信&短信
     * @return array
     */
    public function automaticPushEd(string $patientId, string $class_id, string $ed_id, string $mode = '1'): array
    {
        //获取患者信息
        $patientField = 'id,name,timeLine';
        $patientWhere[] = ['patientId', '=', $patientId];
        $patientInfo = (new PatientInfoModel())->getOneData($patientWhere, $patientField);
        if (empty($patientInfo)) {
            throw new FileException("未查询到患者");
        }

        //获取宣教信息
        $edField = 'id,name';
        $edWhere[] = ['id', '=', $ed_id];
        $edWhere[] = ['classify.value', '=', $class_id];
        $edInfo = (new EdModel())->where($edWhere)->field($edField)->find();
        if (empty($edInfo)) {
            throw new FileException("未查询到宣教信息");
        }

        //获取宣教分类信息
        $classField = 'id,name';
        $classWhere[] = ['id', '=', $class_id];
        $classInfo = (new EdClassModel())->where($classWhere)->field($classField)->find();

        $history_id = new ObjectId();
        $pushData = [
            '_id' => $history_id,
            'type' => 1,
            'pid' => $patientInfo['id'],
            'name' => $patientInfo['name'],
            'patientId' => $patientId,
            'class_id' => $classInfo['id'],
            'class_name' => $classInfo['name'],
            'ed_id' => $edInfo['id'],
            'ed_name' => $edInfo['name'],
            'department_id' => $patientInfo['timeLine'][0]['dept_id'] ?? '',
            'department_name' => $patientInfo['timeLine'][0]['deptName'] ?? '',
            'isview' => 0,
            'status' => 1,
            'mode' => $mode,
            'deleted_at' => 0,
            'pushtime' => date('Y-m-d H:i'),
            'pushtime_ymd' => date('Y-m-d'),
            'source' => 2
        ];

        $messageData = [
            'type' => 2,//消息类型 1随访，2宣教
            'typeName' => '宣教',
            'mode' => $mode,
            'ed_id' => $edInfo['id'],
            'ed_name' => $edInfo['name'],
            'class_id' => $classInfo['id'],
            'class_name' => $classInfo['name'],
            'deleted_at' => 0,
            'patientId' => $patientId,
            'pushtime' => date('Y-m-d'),
            'pushdatetime' => date('Y-m-d H:i'),
            'content' => '您好' . $patientInfo['name'] . ',为您推送' . $edInfo['name'] . '宣教内容',
            'history_id' => (string)$history_id,
            'isview' => 0,
            'category' => 'Patient'
        ];
        try {
            (new PEHModel())->addData($pushData);
            (new MessageModel())->save($messageData);
            return [
                'history_id' => (string)$history_id
            ];
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }

    /**
     * 异常问卷表单推送宣教
     * @param string $answer_id 答案id
     * @param array $ed_id 宣教id
     * @param string $mode 推送类型 1微信，2短信，3微信&短信
     * @retrun bool
     */
    public function pushProjectEd(string $answer_id, array $ed_id = [], string $mode = '1'): bool
    {
        try {
            $cursor = (new Answer())->getAnswerById($answer_id);
            $projectInfo = iterator_to_array($cursor);

            //宣教id不为空则推送宣教
            if (!empty($ed_id)) {
                $pushData = [];
                $messageData = [];
                $eds = (new EdModel())->whereIn('id', $ed_id)->select();
                foreach ($eds as $key => $val) {
                    $history_id = new ObjectId();
                    $pushData[] = [
                        '_id' => $history_id,
                        'type' => 1,
                        'name' => $projectInfo['name'],
                        'patientId' => $projectInfo["patient_id"],
                        'ed_id' => $val['id'],
                        'ed_name' => $val['name'],
                        'isview' => 0,
                        'status' => 1,
                        'mode' => $mode,
                        'deleted_at' => 0,
                        'pushtime' => date('Y-m-d H:i'),
                        'pushtime_ymd' => date('Y-m-d'),
                        'source' => 3,
                        'creator_id' => $projectInfo['creator_id'],
                        'creator_name' => $projectInfo['creator_name'],
                        'department_id' => $projectInfo['creator_dept_id'],
                        'department_name' => $projectInfo['creator_dept_name']
                    ];

                    $messageData[] = [
                        'type' => 2,//消息类型 1随访，2宣教
                        'typeName' => '宣教',
                        'mode' => $mode,
                        'ed_id' => $val['id'],
                        'ed_name' => $val['name'],
                        'deleted_at' => 0,
                        'patientId' => $projectInfo["patient_id"],
                        'pushtime' => date('Y-m-d'),
                        'pushdatetime' => date('Y-m-d H:i'),
                        'content' => '您好' . $projectInfo['name'] . ',为您推送' . $val['name'] . '宣教内容,请查阅',
                        'history_id' => (string)$history_id,
                        'isview' => 0,
                        'category' => 'Patient'
                    ];
                }
                (new PEHModel())->saveAll($pushData);
                (new MessageModel())->saveAll($messageData);
            }

            //获取随访计划名称
            $follow = (new TaskModel())->where('id', $projectInfo['task_id'])->field('taskname')->find();

            //推送消息
            $messageDoctorData = [
                'type' => 7,
                'typeName' => '异常表单',
                'pushtime' => date('Y-m-d'),
                'pushdatetime' => date('Y-m-d H:i:s'),
                'creator_id' => $projectInfo['creator_id'],
                'creator_name' => $projectInfo['creator_name'],
                'doctor_code' => (new UserModel())->where('id', $projectInfo['creator_id'])->value('doctor_code'),
                'task_id' => $projectInfo['questions']['projectId'],
                'title' => $projectInfo['questions']['name'],
                'answer_id' => $answer_id,
                'content' => '您的患者' . $projectInfo['name'] . '在' . $follow['taskname'] . '随访中的' . $projectInfo['questions']['name'] . '问卷调查中存在异常情况，请进行确认。',
                'deleted_at' => 0,
                'isview' => 0,
                'category' => 'Doctor'
            ];
            (new MessageModel())->save($messageDoctorData);
        } catch (\Exception $exception) {
            //日志
            Log::error($exception->getMessage());
        } finally {
            return true;
        }
    }

    /**
     * 绑定推送宣教
     * @param string $patientId 患者Id
     * @param array $ed 宣教参数
     */
    public function pushBindEd(string $patientId, array $ed = [])
    {
        if (empty($ed) || empty($patientId)) {
            throw new FailedException('缺少参数');
        }

        //获取患者信息
        $patientField = 'id,name,timeLine';
        $patientWhere[] = ['patientId', '=', $patientId];
        $patientInfo = (new PatientInfoModel())->getOneData($patientWhere, $patientField);
        if (empty($patientInfo)) {
            throw new FileException("未查询到患者");
        }

        $data = [];
        foreach ($ed as $key => $val) {
            $data[] = [
                'type' => 1,
                'pid' => $patientInfo['id'],
                'name' => $patientInfo['name'],
                'patientId' => $patientId,
                'class_id' => $val['class_id'],
                'class_name' => $val['class_name'],
                'ed_id' => $val['ed_id'],
                'ed_name' => $val['ed_name'],
                'pushtime' => date('Y-m-d H:i'),
                'pushtime_ymd' => date('Y-m-d'),
                'source' => 4,
                'isview' => 0,
                'status' => 1,
                'deleted_at' => 0,
                'department_id' => $patientInfo['timeLine'][0]['dept_id'] ?? '',
                'department_name' => $patientInfo['timeLine'][0]['deptName'] ?? '',
            ];
        }
        $ret = (new PEHModel())->saveAll($data);
        if (!empty($ret)) {
            return $ret->visible(["id", "ed_id", "ed_name", "name", "class_id", "class_name"])->toArray();
        }
        return [];
    }
}